package com.xisoft.common.pubEnv;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * *
 * Created with Description: java汉字转拼音(全拼、简拼)
 *
 * @version 1.0 <br>
 * @packagename: com.xisoft.common<br>
 * @author: LiBencheng <br>
 * @computer: licheng <br>
 * @date: Created on 2022/9/27 10:54 <br>
 */
public class PinYinUtil
{
    /************************************************************* <br>
     *
     *说明: 转全拼<br>
     *
     * @Description   <br>
     * @Date Created on 2022/9/27  13:38  <br>
     * @param str <br>
     * @return java.lang.String  <br>
     * @Author LIBENCHENG
     * @version 1.0 <br>
     ************************************************************* <br>
     */
    public static String convertSimpleSpelling(String str)
    {
        String convert = "";
        if (str == null || str.length() == 0)
        { return convert; }
        for (int j = 0; j < str.length(); j++)
        {
            char word = str.charAt(j);
            // 提取汉字的首字母
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null)
            { convert += pinyinArray[0].charAt(0); }
            else
            { convert += word; }
        }
        return convert.toUpperCase();
    }

    /************************************************************* <br>
     *
     *说明: 转简拼<br>
     *
     * @Description   <br>
     * @Date Created on 2022/9/27  13:38  <br>
     * @param china <br>
     * @return java.lang.String  <br>
     * @Author LIBENCHENG
     * @version 1.0 <br>
     ************************************************************* <br>
     */
    public static String convertAllSpells(String china) throws BadHanyuPinyinOutputFormatCombination
    {
        HanyuPinyinOutputFormat formart = new HanyuPinyinOutputFormat();
        formart.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        formart.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        formart.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] arrays = china.trim().toCharArray();
        String result = "";

        for (int i = 0; i < arrays.length; i++)
        {
            char ti = arrays[i];
            if (Character.toString(ti).matches("[\\u4e00-\\u9fa5]"))
            {
                //匹配是否是中文
                String[] temp = PinyinHelper.toHanyuPinyinStringArray(ti, formart);
                result += temp[0];
            }
            else { result += ti; }
        }

        return result;
    }
}
